package com.hzh.scala

import java.sql.{Connection, DriverManager, PreparedStatement, ResultSet}

object Demo24JDBC {
  /**
   * 在scala语法中链接数据库
   */

  def main(args: Array[String]): Unit = {
    //需要先在pom中增加mysql驱动的依赖
    //1、加载驱动
    Class.forName("com.mysql.jdbc.Driver")
    //2、建立数据库连接
    val conn: Connection = DriverManager.getConnection("jdbc:mysql://master/test?useUnicode=true&characterEncoding=UTF-8", "root", "123456")
    //3、编写sql查询数据
    val sta: PreparedStatement = conn.prepareStatement("select * from student where clazz=?")
    //赋值
    sta.setString(1,"理科二班")
    //5、执行查询语句
    val set: ResultSet = sta.executeQuery()
    //解析数据
    while (set.next()){
      //通过列名取出数据
      val id: Long = set.getLong("id")
      val name: String = set.getString("name")
      val age: Long = set.getLong("age")
      val gender: String = set.getString("gender")
      val clazz: String = set.getString("clazz")
      println(s"$id\t$name\t$age\t$gender\t$clazz")
    }
    //7、关闭连接
    sta.close()
    conn.close()
  }

}
